<template>
  <div>
    <!-- 基础信息 -->
    <div class="basic-information myItem">
      <div class="title-text">基础信息 <span v-if='result'>{{result.lineName}}</span>
        <a-icon :type="isHome?'home':'rollback'" @click="rollback()" :style="{ fontSize: '20px', color: '#ccc' }" />
      </div>
      <div class="information-item" v-if='result'>
        <span>所属站台：{{result.platformName}}</span>
        <span>所属类别：{{result.deviceCategory}}</span>
        <span>所属位置：{{result.deviceLocation}}</span>
        <span>设备名称：{{fDeviceName}}</span>
        <span>设备类型：{{result.deviceType}}</span>
        <span>部件名称：{{result.deviceName}}</span>
      </div>

    </div>
    <!-- 运行报表 -->
    <!-- table区域-begin -->
    <div class="table-list myItem">
      <div class="title-text">部件实时运行报表</div>
      <a-table :rowClassName='rowClassName' ref="table" size="middle" rowKey="id" :columns="columns" :dataSource="dataSourceData" :pagination="false" class="j-table-force-nowrap">

      </a-table>
    </div>

    <div style="height: 10px;width: 110%; background-color: #eff1f4;overflow: hidden;"></div>

    <div class="graphical-report myItem">

      <div class="condition">
        <div class="title">图形列表</div>
        <div class="query-criteria">
          <!-- <span class="dataType" v-for="i in chartDate" :key="i.value" :class="currentTab==i.value?'active':''" @click="clickQuery(i.value)">{{i.name}}</span> -->
          <a-form-model ref="advancedSearchForm">
            <a-form-model-item>
              <!-- <a-range-picker style="width:330px;" v-model="reviewDate" :show-time="{ format: 'HH:mm:00' }" format="YYYY-MM-DD HH:mm:00" @change="onChange" /> -->
              <a-date-picker v-model="reviewDate" :disabled-date='disabledEndDate' style="width:100%" valueFormat="YYYY-MM-DD HH:mm:00" :show-time="{ format: 'HH:mm:00' }" />
            </a-form-model-item>
          </a-form-model>
          <div style="margin-left:10px;">
            <a-button type="primary" icon="search" @click="handleSearch()">查询</a-button>
            <a-button type="primary" icon="sync" ghost style="margin-left:8px;" @click="dateReset">重置</a-button>
          </div>
        </div>
      </div>

      <a-spin :spinning="lineChartLoading" tip="数据加载中">
        <smooth-chart v-if="typeName=='A门电机'||typeName=='B门电机'" :lineData="lineData" :selectedStatus='selectedStatus' @getLegendStatus='getLegendStatus' :curNum="curNum" @resetCurNum="curNum=1">
        </smooth-chart>
        <line-chart v-else :lineData="lineData" :selectedStatus='selectedStatus' :isSmooth="typeName=='A门电子锁'||typeName=='B门电子锁'" @getLegendStatus='getLegendStatus'></line-chart>
      </a-spin>
      <a-button type='primary' ghost class="preBtn" @click='handlePre'>前一分钟</a-button>
      <a-button type='primary' :disabled='isDisable' ghost class="nextBtn" @click='handleNext'>后一分钟</a-button>
      <div class="btnGroup" v-if="typeName=='A门电机'&&maxNum>1||typeName=='B门电机'&&maxNum>1">
        <a-button type='primary' ghost style='margin-right:10px;' @click="preGroup" :disabled="curNum<=1">上一条</a-button>
        <a-button type='primary' ghost @click="nextGroup" :disabled="curNum==maxNum">下一条</a-button>
      </div>
    </div>
  </div>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import LineChart from './modules/LineChart.vue'
import smoothChart from './modules/smoothChart.vue'
import { getAction } from '@/api/manage'
import moment from 'moment';
export default {
  name: 'dcuDetail',
  inject: ['closeCurrent'],
  mixins: [mixinDevice],
  props: {
    equipData: {
      type: Object
    }
  },
  components: {
    LineChart,
    smoothChart
  },
  data() {
    return {
      description: 'dcu详情页',
      dataSourceData: [],
      reviewDate: '',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // 表头
      columns: [
        {
          title: '数据类型名称',
          align: "center",
          dataIndex: 'dataTypeName'
        },
        {
          title: '数据值',
          align: "center",
          dataIndex: 'dataValue'
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit'
        }


      ],
      chartDate: [
        { name: '今日', value: '1' },
        { name: '本周', value: '2' },
        { name: '本月', value: '3' },
        { name: '全年', value: '4' },

      ],
      currentTab: 2,
      isPSD: '',
      timers: null,
      result: null,
      lineData: null,
      lineChartLoading: false,
      typeName: '',
      isDisable: false,
      fDeviceName: '',
      selectedStatus: {},
      curNum: 1,
      maxNum: null,
      deepData: null,
      isHome:false
    }
  },
  watch: {
    'result.alias': {
      handler(val) {
        if (val) {
          this.handleSearch(this.reviewDate)
        }
      }
    },
    reviewDate(val) {
      if (val >= moment().format("YYYY-MM-DD HH:mm:00")) {
        this.isDisable = true
      } else {
        this.isDisable = false
      }
    },
    curNum: {
      handler(val) {
        let dataObj = this.deepData['速度曲线']
        if (dataObj) {
          if (val && val <= this.maxNum) {
            let data = Object.entries(dataObj).sort().filter(([key]) => key == '时间,ms' || key.indexOf('线' + this.curNum + ',') > -1)
            this.lineData = Object.fromEntries(data)
            console.log('watch>>>>>', this.lineData)
          }
        }
      },
      // immediate:true 
    }
  },
  created() {
    let id = this.$route.query.id
    this.isHome = this.$route.query.isHome
    this.typeName = this.$route.query.type
    this.fDeviceName = this.$route.query.fName
    console.log('部件实时运行报表页面ID==》》》', id)
    console.log('部件实时运行报表页面type==》》》', this.typeName)

    this.getListById(id)

    this.timers = setInterval(() => {
      setTimeout(() => {
        this.getListById(id)
      }, 0);
    }, 1000)

    this.reviewDate = moment().format("YYYY-MM-DD HH:mm:00")
  },
  beforeDestroy() {
    clearInterval(this.timers)
    this.timers = null
  },
  computed: {

  },
  methods: {
    rowClassName(row,index){
      return row.dataTypeName.includes('次数')?'rowSelect':''
    },    
    getListById(id) {
      getAction('/basic/gdDevice/queryById', { id }).then(res => {
        if (res && res.code == 200) {
          // console.log('部件实时运行报表 :>> ', res.result.dataTypeList);
          this.result = res.result
          console.log('PSD部件详情==》', this.result)
          this.dataSourceData = res.result.dataTypeList
        }
      })
    },
    disabledEndDate(endValue) {
      return endValue.valueOf() > moment().valueOf();
    },
    getLegendStatus(val) {
      // console.log('getLegendStatus>>>>',val)
      this.selectedStatus = val
    },
    handleSearch(time) {
      if (this.reviewDate >= moment().format("YYYY-MM-DD HH:mm:00")) {
        this.isDisable = true
      } else {
        this.isDisable = false
      }
      this.lineChartLoading = true
      console.log('日期==》》》》', this.reviewDate)
      let params = {
        id: this.result.id,
        alias: this.result.alias,
        deviceLocation: this.result.deviceLocation,
        deviceName: this.fDeviceName,
        // startTime: this.reviewDate[0],
        endTime: time || this.reviewDate
      }
      getAction('/statistics/queryChartById', params).then(res => {
        if (res && res.code == 200) {
          this.maxNum = null
          console.log('图表数据==》》', res.result)

          this.deepData = JSON.parse(JSON.stringify(res.result))
          this.lineData = res.result

          if (this.lineData['速度曲线']) {
            this.maxNum = this.lineData['速度曲线']['total'][0]
            console.log(`当前有>>>>${this.maxNum}组!!!!!`)

            let arr = Object.entries(this.lineData['速度曲线']).sort()
            let first = arr.filter(([key]) => key == '时间,ms' || key.indexOf('线' + this.curNum + ',') > -1)
            this.lineData = Object.fromEntries(first)

          }


          this.lineChartLoading = false
        } else {
          this.$message.info(res.message)
        }
      }).finally(() => {
        this.lineChartLoading = false
      })
    },
    dateReset() {
      this.reviewDate = moment().format("YYYY-MM-DD HH:mm:00")
    },
    handlePre() {
      this.reviewDate = moment(this.reviewDate).subtract(1, 'minutes').format('YYYY-MM-DD HH:mm:00')
      this.handleSearch(this.reviewDate)
    },
    handleNext() {
      this.reviewDate = moment(this.reviewDate).add(1, 'minutes').format('YYYY-MM-DD HH:mm:00')
      let curTime = moment().format('YYYY-MM-DD HH:mm:00')
      if (this.reviewDate >= curTime) {
        this.reviewDate = curTime
        this.handleSearch(curTime)
        return
      }
      this.handleSearch(this.reviewDate)
    },
    preGroup() {
      this.curNum -= 1
      // this.handleSearch(this.reviewDate)
    },
    nextGroup() {
      this.curNum += 1
      // console.log('this.curNum>>>>',this.curNum)
      // this.handleSearch(this.reviewDate)

    },
    clickQuery(val) {
      this.currentTab = val
    },
    onChange(date, dateString) {
      console.log(dateString);
      this.reviewDate = dateString
    },
    rollback() {
      if(this.isHome){
        this.$router.push('/statistics/dataKanban')
        let deviceCategory = this.result.deviceCategory=='半高站台门'?'HALF_HEIGHT':'FULL_HEIGHT'
        let id = this.result.parentId
        setTimeout(()=>{
          this.$EventBus.$emit('showDetail',deviceCategory,{id})
        },0)
        this.closeCurrent()
      }else{
        console.log('this.result.parentId', this.result.parentId)
        this.$router.push({ path: '/equipment/equipmentList/detail', query: { id: this.result.parentId } })
      }
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';

.basic-information {
  padding: 0 0 10px 0;
}

.title-text {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  margin-bottom: 20px;
}

.information-item {
  display: flex;
  justify-content: space-between;
}

.table-list {
  margin-top: 10px;
}

.graphical-report {
  margin-top: 10px;
  position: relative;
  .condition {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    // border: 2px solid red;
    .title {
      font-size: 16px;
      font-weight: 600;
    }
    .query-criteria {
      display: flex;
      align-items: center;
      margin-left: 100px;
      .dataType {
        display: block;
        cursor: pointer;
        height: 28px;
        line-height: 28px;
        padding: 0 7px;
        margin-right: 10px;
        &.active {
          color: #fff;
          background: #1890ff;
          border-radius: 5px;
        }
      }
      .ant-form {
        .ant-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
}
.myItem {
  background: #fff;
  padding: 20px;
}
.preBtn {
  position: absolute;
  left: 20px;
  bottom: 10px;
}
.nextBtn {
  position: absolute;
  right: 20px;
  bottom: 10px;
}
.btnGroup {
  position: absolute;
  right: 120px;
  bottom: 10px;
}
/deep/.rowSelect {
  background: #E8F6EF;
}
</style>